<template>  
    <div>  
      <video ref="localVideo" autoplay muted></video>  
      <video ref="remoteVideo" autoplay></video>  
      <button @click="startCall">开始呼叫</button>  
      <button @click="hangUp">挂断</button>  
    </div>  
  </template>  
    
  <script setup>  
  import { ref, onMounted, onUnmounted } from 'vue';  
    
  const localVideo = ref(null);  
  const remoteVideo = ref(null);  
  const peerConnection = ref(null);  
    
  const peerConnectionConfig = {  
    iceServers: [  
      {  
        urls: 'stun:stun.l.google.com:19302'  
      }  
    ]  
  };  
    
  let socket = null;  
    
  async function startCall() {  
    if (!socket) {  
      socket = new WebSocket('ws://localhost:8000');  
      socket.onmessage = handleMessage;  
      socket.onopen = () => console.log('WebSocket连接已打开');  
      socket.onerror = (error) => console.error('WebSocket错误:', error);  
    }  
    
    peerConnection.value = new RTCPeerConnection(peerConnectionConfig);  
    peerConnection.value.ontrack = (event) => {  
      remoteVideo.value.srcObject = event.streams[0];  
    };  
    
    const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });  
    localVideo.value.srcObject = stream;  
    stream.getTracks().forEach((track) => peerConnection.value.addTrack(track, stream));  
    
    const offer = await peerConnection.value.createOffer();  
    await peerConnection.value.setLocalDescription(offer);  
    socket.send(JSON.stringify({ type: 'offer', offer: offer }));  
  }  
    
  function hangUp() {  
    if (peerConnection.value) {  
      peerConnection.value.close();  
      peerConnection.value = null;  
    }  
    if (socket) {  
      socket.close();  
      socket = null;  
    }  
  }  
    
  async function handleMessage(event) {  
    const data = JSON.parse(event.data);  
    const { peerConnection: pc } = peerConnection.value;  
    
    switch (data.type) {  
      case 'offer':  
        pc.setRemoteDescription(new RTCSessionDescription(data.offer));  
        const answer = await pc.createAnswer();  
        await pc.setLocalDescription(answer);  
        socket.send(JSON.stringify({ type: 'answer', answer: answer }));  
        break;  
      case 'answer':  
        pc.setRemoteDescription(new RTCSessionDescription(data.answer));  
        break;  
      case 'candidate':  
        const candidate = new RTCIceCandidate(data.candidate);  
        pc.addIceCandidate(candidate);  
        break;  
    }  
  }  
    
  onMounted(async () => {  
    // 初始化peerConnection并监听必要的事件  
    peerConnection.value = new RTCPeerConnection(peerConnectionConfig);  
    peerConnection.value.onicecandidate = (event) => {  
      if (event.candidate) {  
        socket.send(JSON.stringify({ type: 'candidate', candidate: event.candidate }));  
      }  
    };  
  });  
    
  onUnmounted(() => {  
    hangUp();  
  });  
  </script>